package com.station.client.dragNDrop;

import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.ui.*;
import com.station.client.Base;
import com.station.client.proxies.PCashOffice;
import com.station.client.proxies.PCoordinates;
import com.station.client.proxies.PPetrolPump;

/**
 * Created with IntelliJ IDEA.
 * User: Jimmy87
 * Date: 16.11.13
 * Time: 22:44
 * To change this template use File | Settings | File Templates.
 */
public class DropCell extends DraggableItem {


    private DraggableContent content;
    final public String defaultUrl = "imgs/road.jpg";
    final public CellTable cellTable;
    final public int absoluteLeft;
    final public int absoluteTop;
    final PCoordinates coordinates;

    public DropCell(CellTable table, int w, int h, int i, int j) {
        //super();
        content = null;
        coordinates = new PCoordinates(i, j);
        absoluteLeft = w * i;
        absoluteTop = h * j;
        setEnable(false);
        this.cellTable = table;
        setUrl(defaultUrl);
        setPixelSize(w, h);
        addDragStartHandler(new DragStartHandler() {
            @Override
            public void onDragStart(DragStartEvent event) {
                if (!enabled)
                    return;
                if (content != null) {
                    event.getDataTransfer().setDragImage(getElement(), 10, 10);   //todo
                    setCurrentItem(content);
                    removeThisContent();
                }
            }
        });

        addDragLeaveHandler(new DragLeaveHandler() {
            @Override
            public void onDragLeave(DragLeaveEvent event) {
                if (enabled && (getCurrentItem() != null || !event.getData("type").equals("")))
                    moveLeave();
            }
        });

        addDragOverHandler(new DragOverHandler() {
            @Override
            public void onDragOver(DragOverEvent event) {
                if (enabled && (getCurrentItem() != null || !event.getData("type").equals("")))
                    moveOver();
            }
        });

        addDropHandler(new DropHandler() {
            @Override
            public void onDrop(DropEvent event) {
                event.preventDefault();
                if (!enabled)
                    return;
                moveLeave();
                String data = event.getData("type");
                boolean isDropItemAvaliable = false;
                if ((coordinates.y < cellTable.gethMAX() - 2) &&
                        (!data.equals("start") && !data.equals("exit") && coordinates.x != cellTable.getwMAX() - 1) ||
                        ((data.equals("start") || data.equals("exit")) && coordinates.x == cellTable.getwMAX() - 1))
                    isDropItemAvaliable = true;
                if (!data.equals("")) {
                    setEnable(true);
                    String url = getUrl(data);
                    if (isDropItemAvaliable) {
                        content = new DraggableContent(data, url, coordinates);//
                        setUrl(url);
                    }
                } else {
                    if (getCurrentItem() != null && isDropItemAvaliable) {
                        content = getCurrentItem();
                        content.setCoordinates(coordinates);
                        if (content.getEntity() instanceof PPetrolPump)
                            ((PPetrolPump) content.getEntity()).initFillingPlace();
                        setEnable(true);
                        setUrl(content.imgUrl);
                        setCurrentItem(null);//remove
                    }
                }
            }
        });

        addMouseDownHandler(new MouseDownHandler() {
            @Override
            public void onMouseDown(MouseDownEvent event) {
                if (!cellTable.isDragMode)
                    createPropertiesPopup();
            }
        });


    }

    public DraggableContent getContent() {
        return content;
    }

    public void setContent(DraggableContent content) {
        this.content = content;
    }


    public void removeThisContent() {
        content = null;
        setUrl(defaultUrl);

    }

    public DraggableContent getCurrentItem() {
        return cellTable.getCurrentItem();
    }

    public void setCurrentItem(DraggableContent item) {
        cellTable.setCurrentItem(item);
    }

    public String getUrl(String key) {
        return cellTable.imgMap.get(key);
    }

    private void moveOver() {
        getElement().getStyle().setOpacity(0.5);
    }

    private void moveLeave() {
        getElement().getStyle().setOpacity(1.0);
    }

    public void createPropertiesPopup() {
        VerticalPanel propertiesPanel = Base.propertiesPanel;
        propertiesPanel.clear();
        propertiesPanel.add(new Label("Параметры объекта"));
        propertiesPanel.setSpacing(5);
        if (content == null)
            return;
        final Class cl = content.getEntityClass();
        Button saveButton = new Button("Сохранить");

        final ListBox fuelList = new ListBox();
        fuelList.addItem("A92");
        fuelList.addItem("A95");
        fuelList.addItem("DIESEL");
        final TextBox fillingSpeed = new TextBox();
        final TextBox maxCashCapacity = new TextBox();
        //

//        if (cl == PFuelTank.class) {
//            PFuelTank entity = (PFuelTank) content.getEntity();
//            maxCapacity.setText(String.valueOf(entity.getMaxCapacity()));
//            int indexToFind = 0;
//            for (int i = 0; i < fuelList.getItemCount(); i++) {
//                if (fuelList.getItemText(i).equals(entity.fuel)) {
//                    indexToFind = i;
//                    break;
//                }
//            }
//
//            fuelList.setSelectedIndex(indexToFind);    //todo
//            Label label1 = new Label("Max capactity");
//            Label label2 = new Label("Fuel type");
//            panel.add(label1);
//            panel.add(maxCapacity);
//            panel.add(label2);
//            panel.add(fuelList);
//        }

        if (cl == PPetrolPump.class) {
            PPetrolPump entity = (PPetrolPump) content.getEntity();
            for (int i = 0; i < fuelList.getItemCount(); i++) {
                if (fuelList.getItemText(i).equals(entity.getFuelType())) {
                    fuelList.setSelectedIndex(i);
                    break;
                }
            }
            Label label1 = new Label("Скорость заправки");
            Label label2 = new Label("Тип топлива");
            fillingSpeed.setText(String.valueOf(entity.getFillingSpeed()));
            propertiesPanel.add(label1);
            propertiesPanel.add(fillingSpeed);
            propertiesPanel.add(label2);
            propertiesPanel.add(fuelList);
        }

        if (cl == PCashOffice.class) {
            PCashOffice entity = (PCashOffice) content.getEntity();
            maxCashCapacity.setText(String.valueOf(entity.getMaxCashAllowed()));
            Label label3 = new Label("Максимальный размер кассы");
            propertiesPanel.add(label3);
            propertiesPanel.add(maxCashCapacity);


        }

        saveButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                if (cl == PPetrolPump.class) {
                    PPetrolPump pump = (PPetrolPump) content.getEntity();
                    pump.setFillingSpeed(Double.parseDouble(fillingSpeed.getText()));
                    pump.setFuelType(fuelList.getValue(fuelList.getSelectedIndex()));
                }
                if (cl == PCashOffice.class) {
                    PCashOffice office = (PCashOffice) content.getEntity();
                    office.setMaxCashAllowed(Double.parseDouble(maxCashCapacity.getValue()));
                }
            }
        });

        propertiesPanel.add(saveButton);
//        RootPanel.get("centerMiddle").clear();
//        RootPanel.get("centerMiddle").add(propertiesPanel);

        //todo offfice
    }


}
